import {
  login,
  register,
  logout,
  getUserinfo,
  getRolesInfobyUsername,
  modifyUserinfo,
  uploadUserAvatarinfo
} from '@/api/user'
import {
  getToken,
  getName,
  getUserCode,
  setToken,
  setName,
  removeTokenAndName,
  removeToken,
  setUserCode
} from '@/utils/auth'
import { SSE } from '@/utils/request'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(), // 先从cookie中获取赋值
    name: getName(), // 先从cookie中获取赋值
    usercode: getUserCode(), // 先从cookie中获取赋值
    username: '', // 用户个人名称
    gender: '', // 个人性别
    region: '', // 来自省会
    hobby: '', // 兴趣爱好
    phone: '', // 电话
    email: '', // 邮箱地址
    memo: '', // 个人说明
    avatar: '', // 头像地址
    avatarGiteeSha: '', // 头像sha值
    roles: [], // 角色列表
    creatTime: '', // 数据创建时间
    updateTime: '' // 上次修改时间
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState()) // 初始化并重置登陆用户信息
  },
  REFLASH_TOKEN: (state, newtoken) => {
    state.token = newtoken
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USER_NAME: (state, name) => {
    state.username = name
  },
  SET_USER_PHONE: (state, phone) => {
    state.phone = phone
  },
  SET_USER_EMAIL: (state, email) => {
    state.email = email
  },
  SET_USER_MEMO: (state, memo) => {
    state.memo = memo
  },
  SET_USER_REGION: (state, region) => {
    state.region = region
  },
  SET_USER_HOBBY: (state, hobby) => {
    state.hobby = hobby
  },
  SET_USER_GENDER: (state, gender) => {
    state.gender = gender
  },
  SET_USER_CODE: (state, usercode) => {
    state.usercode = usercode
  },
  SET_USER_CRETTIME: (state, time) => {
    state.creatTime = time
  },
  SET_USER_UPDATIME: (state, time) => {
    state.updateTime = time
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_AVATAR_SHA: (state, sha) => {
    state.avatarGiteeSha = sha
  },
  SET_AVATAR_FILENAME: (state, name) => {
    state.avatarFileName = name
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user/login-- 用户登陆
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ userName: username.trim(), userPwd: password }).then(response => {
        const { token } = response.data.respOutMsgHeader
        const { userCode } = response.data.main
        commit('SET_USER_CODE', userCode) // 设置用户编号方便使用
        commit('SET_TOKEN', token)
        commit('SET_NAME', username)// 存储登陆的用户名
        setToken(token)// 存在cookie中
        setName(username)// 存在cookie中，用于刷新重新获取并赋值vuex中使用
        setUserCode(userCode) // 存在cookie中
        // 登陆成功时调用sse进行连接，需要存储cookie 用户名后 进行 否则sse连接名为undefind
        SSE()
        resolve(response.data.main)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user/register-- 用户注册
  register({ commit }, user) {
    const { username, password } = user
    return new Promise((resolve, reject) => {
      register({ userName: username.trim(), userPwd: password }).then(response => {
        resolve(response.data.respOutMsgHeader)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 修改用户信息
  modifyInfo({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      modifyUserinfo(userInfo).then(response => {
        const { data } = response
        if (data.main === null) { // 校验响应结果
          resolve(data)
        }
        // 设置用户信息数据
        const { memo, email, phone, hobby, region, gender, name, avatar, creatTime, updateTime } = data.main
        // // 先初始化state内容 角色内容会丢失，直接赋值会覆盖吗？
        // commit('RESET_STATE')
        // 重新设置新数据
        commit('SET_USER_NAME', name) // 存储用户个人昵称
        commit('SET_USER_EMAIL', email)// 存储用户个人邮箱
        commit('SET_USER_MEMO', memo)// 存储用户个人说明
        commit('SET_USER_PHONE', phone)// 存储用户个人电话
        commit('SET_USER_HOBBY', hobby)// 存储用户个人兴趣爱好
        commit('SET_USER_REGION', region)// 存储用户个人来源省会名称
        commit('SET_USER_GENDER', gender)// 存储用户个人性别
        commit('SET_USER_CRETTIME', creatTime)// 存储用户个人信息创建时间
        commit('SET_USER_UPDATIME', updateTime)// 存储用户个人修改时间
        commit('SET_AVATAR', avatar)// 存储用户头像路径
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 保存用户上传的头像地址到用户信息表中
  setAvatar({ commit }, dataobj) {
    return new Promise((resolve, reject) => {
      uploadUserAvatarinfo(dataobj).then(response => {
        const avatar = dataobj.avatar
        const sha = dataobj.avatarGiteeSha
        const avatarFileName = dataobj.avatarFileName
        // 设置用户信息数据
        commit('SET_AVATAR', avatar) // 存储用户头像路径
        commit('SET_AVATAR_SHA', sha) // 存储用户头像sha值
        commit('SET_AVATAR_FILENAME', avatarFileName) // 存储用户头像文件名称
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get userinfo -- 获取用户信息（用户名，角色）
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserinfo(state.usercode).then(response => {
        const { data } = response
        if (data.main === null) { // 校验响应结果
          resolve(data)
        }
        // 设置用户信息数据
        const { memo, email, phone, hobby, region, gender, name, avatar, avatarGiteeSha, avatarFileName, creatTime, updateTime } = data.main
        commit('SET_USER_NAME', name) // 存储用户个人昵称
        commit('SET_USER_EMAIL', email)// 存储用户个人邮箱
        commit('SET_USER_MEMO', memo)// 存储用户个人说明
        commit('SET_USER_PHONE', phone)// 存储用户个人电话
        commit('SET_USER_HOBBY', hobby)// 存储用户个人兴趣爱好
        commit('SET_USER_REGION', region)// 存储用户个人来源省会名称
        commit('SET_USER_GENDER', gender)// 存储用户个人性别
        commit('SET_USER_CRETTIME', creatTime)// 存储用户个人信息创建时间
        commit('SET_USER_UPDATIME', updateTime)// 存储用户个人修改时间
        commit('SET_AVATAR', avatar)// 存储用户头像路径
        commit('SET_AVATAR_SHA', avatarGiteeSha) // 存储用户头像sha值
        commit('SET_AVATAR_FILENAME', avatarFileName) // 存储用户头像文件名称
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取用户角色
  getUserRolesInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getRolesInfobyUsername(state.name).then(response => {
        const { data } = response
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        const { main } = data
        // roles must be a non-empty array -- roles必须是不为空的数组
        if (!main || main.length <= 0) {
          reject('getUserRolesInfo: roles 必须是一个不为空的数组!')
        }
        const role_container = {
          rolesArrays: [],
          rolseCodeArrays: []
        }
        main.forEach(role_obj => {
          // 转化角色存储数组格式 such as: ['admin'] or ,['developer','editor']
          role_container.rolesArrays.push(role_obj.roleName)
          role_container.rolseCodeArrays.push(role_obj.roleCode)
        })
        commit('SET_ROLES', main)// 存储用户角色对象
        resolve(role_container)// 处理过的角色数组对象返回出去用于动态路由的生成和过滤
      }).catch(error => {
        reject(error)
      })
    })
  },
  // // 获取用户个人信息
  // getUserPersonInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getPersonInfobyUsername(state.name).then(response => {
  //       const { data } = response
  //       if (!data) {
  //         reject('Verification failed, please Login again.')
  //       }
  //
  //       const { roles, avatar } = data
  //
  //       // roles must be a non-empty array -- roles必须是不为空的数组
  //       if (!roles || roles.length <= 0) {
  //         reject('getInfo: roles must be a non-null array!')
  //       }
  //       commit('SET_AVATAR', avatar)// 存储用户权限
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },
  // user logout
  logout({ commit, state }) {
    removeTokenAndName() // must remove  token  first 从cookie中清除token值
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('RESET_STATE')
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first 从cookie中清除token值
      commit('RESET_STATE')
      resolve()
    })
  },
  // reflash token
  reflashToken({ commit }, newToken) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first 从cookie中清除token值
      setToken(newToken)// 重新设置cookie新的有效token
      commit('REFLASH_TOKEN', newToken)
      console.log('刷新的token为：' + newToken)
      resolve()
    })
  }
}
export default {
  // 使其成为带命名空间的模块
  namespaced: true,
  state,
  mutations,
  actions
}

